package com.spc.service;

import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.spc.pojo.Product;
import com.spc.pojo.ProductOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.Date;
import java.util.Random;
import java.util.UUID;

/**
 * @author smark
 */
@Service
@DefaultProperties(defaultFallback = "defaultFallbackError")//降级全局使用
public class ProductOrderServiceImp implements IProductOrderService {

    @Autowired
    private RestTemplate restTemplate;

    /**
     * 下单
     * @param userId
     * @param productId
     * @return
     */
    @HystrixCommand//fallbackMethod = "saveOrderError"  //降级局部方法使用
    public ProductOrder saveOrder(Integer userId, Integer productId) {

        if(productId==1){
            throw new RuntimeException();
        }

        //直连管理不方便：eureka
        //负载均衡：ribbon dubbo
        //服务可能报错：怎么处理异常 hystrix
        String url = "http://product-service/getproduct/"+productId;
        Product product = restTemplate.getForObject(url, Product.class);

        //下订单
        ProductOrder productOrder = new ProductOrder();
        productOrder.setId(new Random().nextInt(10000));
        productOrder.setTradeNo(UUID.randomUUID().toString());
        productOrder.setPrice(product.getPrice());
        productOrder.setProductName(product.getTitle());
        productOrder.setUserId(userId);
        productOrder.setCreateTime(new Date());
        return productOrder;
    }

    public ProductOrder saveOrderError(Integer userId, Integer productId){
        ProductOrder productOrder = new ProductOrder();
        productOrder.setId(-1);
        productOrder.setProductName("服务器正忙，请稍后");
        return productOrder;

    }

    public ProductOrder defaultFallbackError(){

        ProductOrder productOrder = new ProductOrder();
        productOrder.setId(-1);
        productOrder.setProductName("服务器正忙，请稍后");
        return productOrder;

    }
}
